<template>
  <div class="myTable">
    <el-form ref="form" :model="form" :rules="rules">
      <el-table
        :key="isKey"
        size="mini"
        style="width:100%;"
        :data="form.tableData"
        :header-cell-style="tableHeaderColor"
        :row-class-name="rowClass"
      >
      <!-- (${form.tableData.filter(i=>i.dataState == '5').length}/${form.tableData.length}) -->
        <el-table-column
          prop="barCode"
          :label="tabState==3?`批次号` : `批次号(${form.tableData.filter(i=>i.dataState == '5').length}/${form.tableData.length})`"
        >
          <template slot-scope="{ row, $index }">
            <div class="flex" :id="'batch'+row.inventoryDetailId">
              <!-- <div class="icon" v-if="tabState != 3">
                <img v-if="row.dataState == 5" src="@/assets/images/gou.png" alt="">
              </div> -->
              <div>
                <van-checkbox
                  v-if="materialEntity.isBatchMag"
                  icon-size="12px"
                  v-model="row.checked"
                  shape="square"
                ></van-checkbox>
              </div>

              <div class="value">
                {{ row.stockInventoryDetailEntity.barCode }}
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column  prop="stockLocationName" label="库位">
          <template slot-scope="{ row, $index }">
            {{row.stockInventoryDetailEntity.stockLocationName}}
          </template>
        </el-table-column>
        <!-- <el-table-column prop="planNum" :label="materialEntity.isDoubleUnit?'计划数量/计量数':'计划入库数'">
            <template slot-scope="{ row, $index }">
              {{materialEntity.isDoubleUnit?(row.planNum+' / '+realNumChange(row.planNum) ):row.planNum}}
          </template>
        </el-table-column> -->
        <el-table-column prop="realNum" :label="materialEntity.isDoubleUnit?'实际数量/计量数':'实际入库数'">
          <template slot-scope="{ row, $index }">
            <el-form-item
             :prop="'tableData.' + $index + '.realNum'"
              :rules="rules.realNum"
            >
              <el-input
              :disabled="tabState != 3"
              v-if="materialEntity.isDoubleUnit"
                @click.native="numDialog(row)"
                readonly=""
                class="myInput"
                size="mini"
                :value="row.realNum+' / '+realNumChange(row.realNum)"
              />
              <el-input
                v-else
              :disabled="tabState != 3"
                @click.native="numDialog(row)"
                readonly=""
                class="myInput"
                size="mini"
                v-model="row.realNum"
              />
            </el-form-item>
  <!-- :disabled="tabState != 3" -->
          </template>
        </el-table-column>
        <el-table-column  prop="stockLocationName" label="生产日期">
          <template slot-scope="{ row, $index }">
            <!-- {{row.stockInventoryDetailEntity.stockLocationName}} -->
             <!-- <div> -->
              <div v-if="!row.isAdd">
                {{ row.stockInventoryDetailEntity.produceTime }}
              </div>
               <div v-else class="select-wrap" @click="dateShowFn(row,$index)">
                   <span class="val" v-if="row.produceTime">{{ row.produceTime }}</span>
                   <span class="txt" v-else>请选择</span>
                   <i class="el-icon-arrow-down down-icon"></i>
               </div>
             <!-- </div> -->
          </template>
        </el-table-column>
      </el-table>
    </el-form>
    <van-calendar v-model="dateShow" color="#548AF1" :min-date="minDate" @confirm="onDateConfirm" />
    <van-dialog
      v-model="showRealNum"
      title="实际入库数"
      show-cancel-button
      confirm-button-color="#548AF1"
      :before-close="beforClose"
      @cancel="realNumHandleCancel"
    >
      <van-form ref="realNumForm" @submit.native.prevent label-width="130px">
        <van-field
          v-model="currentRow.planNum"
          type="number"
          label="计划数量"
          readonly
        />
        <van-field
        v-if="materialEntity.isDoubleUnit"
          v-model="calcPlanNum"
          type="number"
          label="计划数量(计量单位)"
          readonly
        />
        <van-field
          name="realNum"
          v-model="realNum"
          type="number"
          label="实际数量"
          :rules="getRealNum()"
          @change="calcRealNum = realNumChange(realNum)"
        />
        <van-field
          v-integer-only
          v-if="materialEntity.isDoubleUnit"
          name="realNum"
          v-model="calcRealNum"
          type="number"
          label="实际数量(计量单位)"
          @change="calcRealNumChange"
        />
      </van-form>
    </van-dialog>
  </div>
</template>
<script>
export default {
  data() {
    var validateRealNum=(rule, value, callback)=>{
      let re =/^[0-9]+.?[0-9]*/
      if(!this.materialEntity.isBatchMag){
        callback();
      }else{
        if (value === '' || !value) {
          callback(new Error('不能为空'));
        } else if (value == 0) {
          callback(new Error('不能为0'));
        } else if(!re.test(value)){
          callback(new Error('不能为非数字'));
        }else{
          callback();
        }
      }
      
    }
    return {
      minDate: new Date(2010, 0, 1),
      isKey:false,
      currentRow:{},
      realNum:"",
      calcRealNum:"",
      calcPlanNum:"",
      showRealNum:false,
      rules:{
        realNum: [
            { validator: validateRealNum, trigger: 'blur' }
        ],
      },
      clickIndex: -1,
      dateShow: false,
    };
  },
  props: {
    tableData: {
      type: Array,
      default: () => {
        return [];
      },
    },
    tabState: {
      type: [Number, String],
    },
    materialEntity: {
      type: Object,
      default: () => ({})
    },
  },
  computed: {
    form(){
      return {
        tableData:this.tableData
      }
    }
  },
  methods: {
    realNumChange(val){
      if(this.materialEntity.isDoubleUnit && this.materialEntity.scaleFactor){
        return  Math.floor(Number((val/(this.materialEntity.scaleFactor||0)).toFixed(4)))
      }
      return ''
    },
    calcRealNumChange(val){
      if(this.materialEntity.isDoubleUnit && this.materialEntity.scaleFactor){
        this.realNum = Number((this.calcRealNum*(this.materialEntity.scaleFactor)).toFixed(4))
      }
    },
    updataTable(){
      this.isKey = !this.isKey
      this.form.tableData = this.tableData
    },
    getRealNum(item) {
      return [
        {
          item,
          validator: this.validatorRealNum,
          message: "实际数量不能为空,不能小于等于0",
          trigger: "onBlur",
        },
      ];
    },
    validatorRealNum(val, rule) {
      if (!val) {
        return false;
      }
      if (val <= 0) {
        return false;
      } else {
        return true;
      }
    },
    beforClose(action,done){
      if (action == "confirm") {
          this.$refs.realNumForm
          .validate("realNum")
          .then(async (res) => {
            this.currentRow.realNum = this.realNum
            this.currentRow.calcRealNum = this.calcRealNum
            this.currentRow = {}
            this.$emit('numDialog')
            done()
          }).catch(err=>{
            done(false)
          })
      }else{
        done()
      }
    },
    // realNumHandleConfirm(){
    //   this.$refs.realNumForm
    //     .validate("realNum")
    //     .then(async (res) => {

    //     })
    //
    // },
    realNumHandleCancel(){
      this.showRealNum = false
    },
    rowClass({ row, rowIndex }) {
      if (row.checked) {
        return "checked-current-row";
      }
      if(row.dataState == 5){
        return 'dataState-5'
      }
    },
    tableHeaderColor({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 0) {
        return "background-color:#F6F6F6;"
      } else {
        return "background:#F6F6F6";
      }
    },
    numDialog(row){
      if(this.tabState != 3){
        return
      } 
      this.currentRow = row
      this.realNum = JSON.parse(JSON.stringify(row)).realNum
      if(this.materialEntity.isDoubleUnit && this.materialEntity.scaleFactor){
        this.calcRealNum = Math.floor(Number((this.realNum/(this.materialEntity.scaleFactor||0)).toFixed(4)))
        this.calcPlanNum = Number((this.currentRow.planNum/(this.materialEntity.scaleFactor||0)).toFixed(4))
      }
      this.showRealNum = true
    },
    dateShowFn(row, index) {
      this.dateShow = true
      this.clickIndex = index
    },
    onDateConfirm(date) {
        this.dateShow = false;
        this.$set(this.form.tableData[this.clickIndex], 'produceTime', this.formatDate(date))
        console.log(this.form.tableData)
    },
    formatDate(val) {
        const date = new Date(val);
        const Y = date.getFullYear();
        const M = date.getMonth() + 1;
        const D = date.getDate();
        const H = date.getHours();
        const Min = date.getMinutes();
        const S = date.getSeconds();
        const formattedDate = `${Y}-${(M < 10 ? '0' : '') + M}-${(D < 10 ? '0' : '') + D} ${(H < 10 ? '0' : '') + H}:${(Min < 10 ? '0' : '') + Min}:${(S < 10 ? '0' : '') + S}`;
        return formattedDate
    },
  },
};
</script>
<style scoped lang="scss">
.myTable {
  border: 1px solid #e9e9e9;
  border-radius: 2px 2px 0px 0px;
  .flex {
    display: flex;
    align-items: center;
  }
  .icon {
    width: 20px;
    display: flex;
    align-items: center;
  }
  .myInput {
    ::v-deep .el-input {
      .el-input__inner {
        height: 22px;
      }
    }
  }
  ::v-deep .el-table__header{
    .el-table__cell{
      .cell{
        padding-left:0 ;
        padding-right:0 ;
      }
    }
  }
  ::v-deep .el-table__row {
    background: #fefcee;
    .el-table__cell {
      background: #fefcee !important;
      .cell{
        padding-left:0 ;
        padding-right:0 ;
      }
      .el-form-item{
        margin: 0;
      }
    }
    &.class {
      .el-table__cell {
        background: #bbffb8 !important;
      }
      background: #bbffb8 !important;
    }
    &.checked-current-row {
      background: #d5e3ff;
      .el-table__cell {
        background: #d5e3ff !important;
      }
    }
    &.dataState-5{
      .el-input__inner{
        background-color: #bbffb8;
        border-color: #bbffb8;
        color: #606266;
      }
      .el-table__cell {
        background: #bbffb8 !important;
      }
      background: #bbffb8 !important;
    }
  }
}
.select-wrap {
    border: 1px solid #DCDFE6;
    background-color: #fff;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 1px 10px;
    border-radius: 4px;
    margin-left: 10px;
    .val {
        color: #333333;
    }

    i {
        margin-left: 5px;
        color: #909090;
    }
}
</style>
